from PySide6.QtCore import Signal, Slot, Signal, QThread, Qt
from PySide6.QtGui import QAction
from PySide6.QtWidgets import QWidget, QMessageBox, QCheckBox, QRadioButton, QPushButton, QComboBox
from Libs.Component.ComboCheckBox import ComboCheckBox
from Forms.SearchFilterForm import SearchFilterForm
from Threads.JinritemaiThread import JinritemaiThread
from . import *
import re


class SearchFilterWidgets(QWidget):
    show = Signal(bool)
    main_cate = {}

    def __init__(self, parent=None, parentWidget=None, showWidgets=True):
        super().__init__(parent)

        self.main_cate = {}

        self.queryBody = {
            'page': 1,
            'refresh': True,
            'type': 1,
            'search_id': '',
            'filters': {
                "content_type": [],
                "total_sales": [],
                "live_total_sales": [],
                "video_total_sales": [],
                "image_text_total_sales": [],
                "windows_total_sales": [],
                "live_sale_avg": [],
                "live_watching_times": [],
                "video_sale_single": [],
                "video_play_time": [],
                "image_text_sale_single": [],
                "image_text_play_time": [],
                "window_order_cnt": [],
                "window_product_cnt": [],
                "main_cate": [],
                "author_level": [],
                "fans_num": [],
                "author_portrait": [],
                "fan_portrait": [],
                "can_connect": [],
                "high_response_rate_im": [],
                "has_contact": [],
                "only_commission": [],
                "commission_quotation": [],
                "sale_reputation": [],
                "merchant_info": []
            }
        }

        self.parentWidget = parentWidget
        self.show.connect(self.parentWidget.searchFilterWidgetsShow)

        self.mainUi = SearchFilterForm()
        if showWidgets:
            self.mainUi.setupUi(self)
            self.mainUi.searchBtn.clicked.connect(self.searchBtnClicked)
            self.setupThread()

    @Slot()
    def searchBtnClicked(self):
        if hasattr(self.mainUi, 'daren_type'):
            item = getattr(self.mainUi, 'daren_type')
            value = 1
            if isinstance(item, QComboBox):
                value = item.currentIndex() + 1
                logging.debug(f'aaaaaaa: {item.currentIndex()} - {value}')
            self.queryBody['type'] = value

        for x in self.queryBody.get('filters'):
            try:
                key = f'query_body_{x}'
                query_body = getattr(self.mainUi, key)
            except AttributeError as e:
                text = re.compile(r".*[0-9]$")
                if text.match(key):
                    logging.debug(f'xxx: {key}')
                else:
                    logging.debug(f'yyy: {key}')
                    continue

            # logging.debug(f'value: {query_body} - {type(query_body)}')
            if isinstance(query_body, QCheckBox) and query_body.isChecked():
                keys = x.replace('query_body_', '').split('_')
                keys.pop()
                key = '_'.join(keys)
                logging.debug(f"QCheckBox, {key} - {query_body.isChecked()}")
            elif isinstance(query_body, QPushButton) and query_body.isChecked():
                key = x.replace('query_body_', '')
                logging.debug(f"QPushButton, {key} - {query_body.isChecked()}")
            elif isinstance(query_body, ComboCheckBox):
                # 先清空旧的，再重新append
                self.queryBody.get('filters')[x] = []
                for val in query_body.getCheckItems():
                    idx = query_body.items.index(val)
                    if idx not in self.queryBody.get('filters')[x]:
                        self.queryBody.get('filters')[x].append(str(idx))

        logging.debug(f'res: {self.queryBody}')
        self.hide()

    def setupThread(self):
        self.jinritemaiThread = JinritemaiThread(cookies=self.parentWidget.cookies, verifyFp=self.parentWidget.verifyFp,
                                                 msToken=self.parentWidget.msToken, screenInfo=self.parentWidget.screenInfo,
                                                 ua=self.parentWidget.userAgent)
        self.thread = QThread()
        self.jinritemaiThread.moveToThread(self.thread)
        self.jinritemaiThread.resp.connect(self.jinritemaiResp)
        self.jinritemaiThread.finished.connect(self.jinritemaiFinished)
        self.thread.started.connect(self.jinritemaiThread.getSearchFilter)
        self.thread.start()

    @Slot()
    def checkboxToggled(self):
        key = self.sender().objectName().replace("query_body_", "")
        logging.debug(f'radio: {key} - {self.sender().isChecked()} - {self.sender().isCheckable()} - {self.sender().checkState()}')
        if self.sender().isChecked():
            self.queryBody['filters'][key] = ["true"]
        else:
            self.queryBody['filters'][key] = []

    @Slot()
    def menuActionTriggered(self):
        logging.debug(f'sender: {self.sender()}')
        nameList = self.sender().objectName().split('_')
        value = nameList.pop(len(nameList) - 1)
        if '|' in value:
            value = value.split('|')
            # valueList = value.split('|')
            # value = valueList[1]
        if nameList:
            actionName = '_'.join(nameList)
            key = actionName.replace('query_body_', '')
            if key in ['fans_gender', 'fans_location', 'fans_age']:
                if not self.queryBody['filters'].get(key, None):
                    self.queryBody['filters'][key] = []
                actionName = f'query_body_fan_portrait'
                self.queryBody['filters']['fan_portrait'] = ['undefined']

            if key in ['author_gender', 'author_location', 'bind_institution']:
                if not self.queryBody['filters'].get(key, None):
                    self.queryBody['filters'][key] = []
                actionName = f'query_body_author_portrait'
                self.queryBody['filters']['author_portrait'] = ['undefined']

            pushButton = getattr(self.mainUi, actionName)
            text = pushButton.text()
            actionText = self.sender().toolTip()
            if not self.sender().isChecked():
                if isinstance(value, list):
                    for removeItem in self.queryBody['filters'][key]:
                        if removeItem in value:
                            self.queryBody['filters'][key].remove(removeItem)
                else:
                    self.queryBody['filters'][key].remove(value)
                textList = text.split(', ')
                textList.remove(actionText)
                text = ','.join(textList)
            else:
                if isinstance(value, list):
                    self.queryBody['filters'][key].extend(value)
                else:
                    self.queryBody['filters'][key].append(value)
                text = text + (', ' if pushButton.text() else '') + f'{actionText}'
            
            pushButton.setText(text)
            pushButton.setToolTip(text)
            

    @Slot()
    def jinritemaiFinished(self):
        self.thread.wait()
        logging.debug(f'jinritemaiFinished: {self.thread.isRunning()}, {self.thread.isFinished()}')
        # self.show.emit(True)

        for x in self.queryBody.get('filters'):
            itemName = f'query_body_{x}'
            if not hasattr(self.mainUi, itemName):
                continue

            query_body = getattr(self.mainUi, itemName)
            if isinstance(query_body, QCheckBox):
                logging.debug(f'QCheckBox itemName: {query_body}')
                query_body.toggled.connect(self.checkboxToggled)
            elif query_body.objectName() in ['query_body_main_cate', 'query_body_author_portrait', 
                                           'query_body_fan_portrait', 'query_body_fan_age']:
                for item in dir(self.mainUi):
                    if item.startswith(query_body.objectName()) and item != query_body.objectName():
                        action = getattr(self.mainUi, item)
                        action.triggered.connect(self.menuActionTriggered)
                    elif query_body.objectName() == 'query_body_fan_portrait' and \
                        ('fans_age' in item or 'fans_gender' in item or 'fans_location' in item):
                        action = getattr(self.mainUi, item)
                        if isinstance(action, QAction):
                            action.triggered.connect(self.menuActionTriggered)
                    elif query_body.objectName() == 'query_body_author_portrait' and \
                        ('bind_institution' in item or 'author_gender' in item or 'author_location' in item):
                        action = getattr(self.mainUi, item)
                        if isinstance(action, QAction):
                            action.triggered.connect(self.menuActionTriggered)


    @Slot(list)
    def jinritemaiResp(self, res):
        logging.debug(f'jinritemaiResp: {not res}')
        if res:
            self.mainUi.parseData(res)
            for info in res:
                for x in info.get('header', []):
                    if not self.queryBody.get('filters', {}).get(x.get('field_name'), None):
                        self.queryBody['filters'][x.get('field_name')] = []
            self.show()
        else:
            self.close()

        self.thread.quit()
        self.show.emit(False if not res else True)

